<?php
namespace Spider\network;

use lactone\Core\data\SocketData;
use lactone\Core\network\ClientInstance;

class SendTaskToServer extends ClientInstance{

    protected $taskQueue;

    private $Process;

    public function run(){
        $Object = $this;

        $this->Process = new \swoole_process(function($worker) use ($Object){

            \Lactone::info("Run in Process!");

            $Object->Process->name("php SendTaskToServer");

            $Object->initClient(false);

            $Object->initTaskQueue();

            $Object->afterToRunTask();

        });

        if($pid = $this->Process->start()){
            \Lactone::saveProcessPid($pid);
        }else{
            exit("SendTaskToServer Process faild!Error:".\swoole_strerror());
        }


    }

    /**
     * 初始化任务队列
     */
    protected function initTaskQueue(){

        \Lactone::info($this->logMessage('初始化队列','SendTaskToServer'));

        if( ($TaskQueue = \Lactone::getConfig('TaskQueue')) && (is_array($TaskQueue)) ){
            $TaskQueue['class'] = '\lactone\Core\Queue\Queue';
            $TaskQueue['ShiftLoopTime'] = 0;
            $this->taskQueue = \Lactone::CreateObject($TaskQueue);

        }else{
            throw new \Exception("need set taskQueue;");
        }

    }

    /**
     * 多少毫秒后自动运行某函数
     * @param int $after
     */
    protected function afterToRunTask($after = 1000){
        \swoole_timer_after($after,array($this,'taskSendToServer'));
    }

    /**
     * 任务发送
     */
    public function taskSendToServer(){
        if(!$this->isConnect){
            $this->initClient(false);
            $this->afterToRunTask(2000);
            return false;
        }

        if(rand(1,500) == 1)
            \Lactone::debug($this->logMessage("taskSendToServer",'SpiderToServer'));

        /**
         * 获取到任务就进行发送
         */
        $i = 0;
        while(!$this->taskQueue->isEmpty()){
            $data = new SocketData();
            if($task = $this->taskQueue->shift()){

                \Lactone::debug($this->logMessage($task,'SpiderToServer'));

                $data->create($task,'task');
                if($this->Send($data->__toString())){
                    $i++;
                    \Lactone::debug($this->logMessage("taskSendSuccess",'SpiderToServer'));
                }else{
                    \Lactone::warning($this->logMessage("taskSendError",'SpiderToServer'));
                }

                if($i>100){
                    sleep(rand(1,4));
                    $i=0;
                }
            }
        }

        $this->afterToRunTask(100);

    }

}